package com.example.wificontroller3;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private URL url;
    private boolean is_running_background;
    private HttpURLConnection httpURLConnection;

    private Button settingButton;
    private CrossPadView mv;
    private WifiUtils wifiutils;
    private TextView SSID_name;
    private TextView SSID_level;
    private static final String TAG = "pad";

    Runnable runnable;

    {
        runnable = () -> captureImage();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);


        try {
            url = new URL(getString(R.string.URL));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        is_running_background = false;

        //设置wifi button
        settingButton = findViewById(R.id.button);
        settingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                startActivity(intent);
            }
        });

        //设置摇杆按键处理
        mv = (CrossPadView) findViewById(R.id.padView);
        mv.setOnDirChangedListener(new CrossPadView.DirChangedListener() {
            @Override
            public void dirChanged(CrossPadView.Direction dir) {
                switch (dir) {
                    case DIRECTION_CENTER:
                        sendCMD_Dir("dir_center");
                        break;
                    case DIRECTION_UP:
                        sendCMD_Dir("dir_up");
                        break;
                    case DIRECTION_DOWN:
                        sendCMD_Dir("dir_down");
                        break;
                    case DIRECTION_LEFT:
                        sendCMD_Dir("dir_left");
                        break;
                    case DIRECTION_RIGHT:
                        sendCMD_Dir("dir_right");
                        break;
                    case DIRECTION_UP_RIGHT:
                        sendCMD_Dir("dir_up_right");
                        break;
                    case DIRECTION_DOWN_RIGHT:
                        sendCMD_Dir("dir_down_right");
                        break;
                    case DIRECTION_UP_LEFT:
                        sendCMD_Dir("dir_up_left");
                        break;
                    case DIRECTION_DOWN_LEFT:
                        sendCMD_Dir("dir_down_left");
                        break;
                }
            }
        });

        SSID_name = findViewById(R.id.SSID);
        SSID_level = findViewById(R.id.SSID_level);
        wifiutils = new WifiUtils(this);
    }

    long timelastTimeMillis = 0L;

    private void sendCMD_Dir(String dir) {
        long timecurrentTimeMillis = System.currentTimeMillis();
        if ((timecurrentTimeMillis - timelastTimeMillis) > 200 || dir == "dir_center") {
            timelastTimeMillis = timecurrentTimeMillis;
            new Thread() {
                public void run() {
                    try {
                        String url = "http://192.168.4.1:8080" + "/?key=" + dir;
                        Log.d(TAG, dir);
                        String html = getHtml(url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

    private String getHtml(String path) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection conn = null;
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    byte[] data = new byte[0];
                    data = StreamTool.read(in);
                    String html = new String(data, "UTF-8");
                    Log.d(TAG, "getHtml: " + html);
                    return html;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void initHttp() {
        try {
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
        } catch (IOException e) {
            e.printStackTrace();
        }
        httpURLConnection.setConnectTimeout(1000 * 5);
        httpURLConnection.setReadTimeout(1000 * 5);
        httpURLConnection.setDoInput(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initHttp();
        refreshWifiInfo();
        is_running_background = false;
        new Thread(runnable).start();
    }

    private void refreshWifiInfo() {
        wifiutils.getConnectedInfo();
        SSID_name.setText(wifiutils.getConnectedSSID());
        SSID_level.setText(wifiutils.getConnectedlevel());
    }

    @Override
    protected void onPause() {
        super.onPause();
        is_running_background = true;
        httpURLConnection.disconnect();
    }

    private void captureImage() {
        if (!is_running_background) {
            BufferedInputStream bufferedInputStream = null;
            try {
                httpURLConnection.connect();

                if (httpURLConnection.getResponseCode() == 200) {
                    InputStream in = httpURLConnection.getInputStream();

                    InputStreamReader isr = new InputStreamReader(in);
                    BufferedReader bufferedReader = new BufferedReader(isr);

                    String line;

                    int len;
                    byte[] buffer;

                    while ((line = bufferedReader.readLine()) != null) {
                        if (is_running_background) {
                            return;
                        }
                        if (line.contains("Content-Type:")) {
                            line = bufferedReader.readLine();

                            len = Integer.parseInt(line.split(":")[1].trim());

                            bufferedInputStream = new BufferedInputStream(in);
                            buffer = new byte[len];

                            int t = 0;
                            while (t < len) {
                                t += bufferedInputStream.read(buffer, t, len - t);
                            }

                            BitmapFactory.Options opts = new BitmapFactory.Options();
                            opts.inJustDecodeBounds = false;//为true时，返回的bitmap为null
                            final Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length, opts);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    imageView.setImageBitmap(bitmap);
                                    refreshWifiInfo();
                                }
                            });
                        }
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bufferedInputStream != null) {
                        bufferedInputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}